<?php

/**
 **	BlockIP类
 **
 **	屏蔽一段IP类
 */
class BlockIP
{
    var $aBlockIP = array();

	//读取屏蔽的IP列表 保存在$this->aBlockIP中
	function getBlockIP()
	{
		if (is_file('block_ip.txt'))
		{
			$block_ip = file('block_ip.txt');
			foreach ($block_ip as $var)
			{
				$this->aBlockIP[] = trim($var);
			}
		}
		//print_r($this->aBlockIP);
	}

	//将屏蔽的IP转换为正则表达式形式
    function getPregIP($blockIP)
	{
		foreach ($blockIP as $var)
		{
			$str = $var;
			$str = str_replace('.','\.',$str);
			$str = str_replace('*','[0-9]{1,3}',$str);
			$pregIP[] = trim($str);
		}
        return $pregIP;
    }

	//检查访问IP是否在屏蔽的IP队列里
    function checkIP()
	{
		$this->getBlockIP();
        $ipTable = $this->getPregIP($this->aBlockIP);
        $isBlocked = true;
        //取得用户ip
        $userIP = $this->getClientIP();
        //屏蔽黑名单中的IP区段
        if ($ipTable)
		{
			foreach($ipTable as $var)
			{
				if (preg_match("/".$var."/",$userIP))
				{
					$isBlocked = false;
					break;
				}
			}
        }
        return $isBlocked;
    }

	//函数getClientIP
	//取得访问用户IP
    function getClientIP()
	{
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
			$ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
			$ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
			$ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
			$ip = $_SERVER['REMOTE_ADDR'];
        else
			$ip = "unknown";
        return trim($ip);
  }
}
?>